package top.akame.webs.utils

import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.file.Files

// 上传工具

@Component
class Uploads {

    @Value("\${ffmpeg.temp}")
    lateinit var temp: String

    /**
     * 给要上传的文件打标记
     * 记录当前上传到第几个了
     */
    fun markStats(flag: String, stats: Int = 0) {
        val folder = File(temp, flag)
        val file = File(folder, "stats")
        if (!folder.exists()) { // 文件夹不存在则新建
            folder.mkdirs()
            file.createNewFile()
        }

        Files.write(file.toPath(), "$stats".toByteArray())
    }

    /**
     * 根据唯一的标识获取要上传文件上传的位置
     */
    fun getStats(flag: String) :Int {
        val file = File(File(temp, flag), "stats")
        if (!file.exists()) return 0
        val bytes = Files.readAllBytes(file.toPath())
        val s = String(bytes)
        return if (s == "") 0 else s.toInt()
    }

    /**
     * 将文件保存为临时文件 增加的形式
     *
     * @param flag 文件的唯一标识
     */
    fun saveToTemp(mlFile: MultipartFile, flag: String) :File {
        val folder = File(temp, flag)
        val temp = getTemp(flag)
        val target = getTempTarget(flag)
        if (!folder.exists()) {
            folder.mkdirs()
        }
        temp.createNewFile()
        if (!target.exists()) {
            target.createNewFile()
        }
        mlFile.transferTo(temp) // 保证当前文件上传完毕

        val stream = FileInputStream(temp)
        val out = FileOutputStream(target, true)
        val buffer = ByteArray(8192 * 8)
        var n = stream.read(buffer)
        while (n != -1) {
            out.write(buffer, 0, n)
            n = stream.read(buffer)
        }
        stream.close()
        out.close()

        temp.delete()
        return target
    }

    fun clearTemp(flag: String) {
        val folder = File(temp, flag)
        val video = File(folder, "temp.video")
        val stats = File(folder, "stats")
        video.delete()
        stats.delete()
        folder.delete()
    }

    fun getTemp(flag: String): File {
        return File(temp, "$flag/temp.video.temp")
    }

    fun getTempTarget(flag: String): File {
        return File(temp, "$flag/temp.video")
    }
}
